#!/usr/bin/python

# Script ini mengasumsikan input adalah komponen header C dari parser
# yang dihasilkan Lemon, menghasilkan kode C berisi array string nama
# token untuk keperluan verifikasi scanner.

import optparse
import os, sys, re, traceback

line_re = re.compile(r"^#define\W+T_(?P<name>\w+)\W+(?P<id>\d+)\W*$")
slot_str = r"/*!TOKENSTR_LIST!*/"

def read_file(fIn):
    if fIn == None: return
    tokenDict = {}
    tokenList = []

    for line in fIn.readlines():
        match_obj = line_re.match(line)
        tokenDict.setdefault(int(match_obj.group('id')), match_obj.group('name'))

    for i in range(max(tokenDict.keys()) + 1):
        tokenList.append('"%s"' % tokenDict.get(i, ""))

    return tokenList

def write_file(fOut, fTemplate, tokenList):
    for line in fTemplate.readlines():
        match_idx = line.find(slot_str)
        if match_idx >= 0:
            fOut.write(",\n".join(tokenList))
        else:
            fOut.write(line)

def process_args():
    parser = optparse.OptionParser()
    parser.add_option('-t', '--template', dest='template')
    opts, args = parser.parse_args()
    return opts, args

if __name__ == '__main__':
    opts, args = process_args()
    if len(args) == 2 and opts.template:
        fIn = None
        fOut = None
        fTemplate = None
        try:
            fIn = open(args[0], 'rb')
            fOut = open(args[1], 'wb')
            fTemplate = open(opts.template, 'rb')
            tokenList = read_file(fIn)
            write_file(fOut, fTemplate, tokenList)
        except:
            traceback.print_exc()
            sys.exit(1)
        finally:
            fIn.close()
            fOut.close()
            fTemplate.close()
